package com.srd.phone.mvp.presenters;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.srd.phone.application.HttpStringRequest;
import com.srd.phone.mvp.interfaces.IBaseView;

import java.lang.ref.WeakReference;
import java.util.Map;


public class BasePresenter {

    protected RequestQueue requestQueue;
    protected WeakReference<IBaseView> iView;

    public BasePresenter(RequestQueue requestQueue0, IBaseView iView0) {
        requestQueue = requestQueue0;
        iView = new WeakReference<IBaseView>(iView0);
    }

    public void cancelRequest(Object obj) {
        if (obj != null) {
            requestQueue.cancelAll(obj);
        }
    }

    /**
     * 网络请求：
     */
    public void requestGetData(final String url) {
        HttpStringRequest request = new HttpStringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                iView.get().returnData(url, response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                iView.get().onError(url, error);
            }
        });
        request.setTag(url);
        requestQueue.add(request);
    }

    /**
     * 网络请求：
     */
    public void requestPostData(final String url) {
        HttpStringRequest request = new HttpStringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                iView.get().returnData(url, response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                iView.get().onError(url, error);
            }
        });
        request.setTag(url);
        requestQueue.add(request);
    }

    /**
     * 网络请求：
     */
    public void requestPostData(final String url, final Map<String, String> map) {
        HttpStringRequest request = new HttpStringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                iView.get().returnData(url, response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                iView.get().onError(url, error);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }
        };
        request.setTag(url);
        requestQueue.add(request);
    }

}
